package com.googlecode.horncomb.util.lang;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.springframework.util.CollectionUtils;

public class CollectionConverter {
	@SuppressWarnings("unchecked")
	public static Collection getPropertyCollection(Collection input,
			final String propertyName) {
		Collection rs = new ArrayList();
		if (input == null) {
			return rs;
		}
		Iterator i = null;
		if (input.getClass().isArray()) {
			i = CollectionUtils.arrayToList(input).iterator();
		} else if (input instanceof Iterable) {
			i = ((Iterable) input).iterator();
		} else if (input instanceof Iterator) {
			i = ((Iterator) input);
		}
		if (i == null) {
			throw new IllegalArgumentException(
					"Only be Array, Iterable or Iterator");
		}
		while (i.hasNext()) {
			Object o = i.next();
			if (o != null) {
				Object val = BeanUtils
						.getNullablePropertyValue(o, propertyName);
				if (val != null) {
					rs.add(val);
				}
			}
		}
		return rs;
	}
}
